<?php
require("libraries/student.php");
class Album extends Student{
	public function __construct(){
		parent::__construct();
		$this->load->helper("url");
		$this->load->helper("form");
		$this->load->library("string");
		$this->load->model("model_albums");
		$this->load->library("string","session");
	}
	public function index(){
		$config['base_url'] = base_url().'admin/album/index/';
		$config['total_rows'] = $this->model_albums->count_all();
		$config['per_page'] = 10;
		$config['uri_segment'] = 4;
		$config['next_link'] = "Next";
		$config['prev_link'] = "Prev";
		$this->load->library("pagination");
		$this->pagination->initialize($config); 
		$start = $this->uri->segment(4);
		$data['data'] = "";
		$data['title'] = "Manage albums";
		$data['template'] = "album/index";
		$data['act'] = 0;
		$data['currentlist']= $this->model_albums->listall($config['per_page'],$start);
		$this->load->view("layout",$data);
	}
	public function add(){
		$data["template"] = "album/add";
		$data["title"] = "Add album";
		$data['data'] = "";
		$data['destinations'] = $this->model_albums->listdestina();
		if($this->input->post("ok")){
			$frienly = str_replace(' ', '-', strtolower($this->string->replace($this->input->post('title'))));
			$db = array(
				"title" => $this->input->post("title"),
				"rewrite" => $frienly,
				"keyword" => $this->input->post("keyword"),
				"description" => $this->input->post("description"),
				"createdate" => date("d/m/Y H:i:s"),
				"destina_id" => $this->input->post("destina_id")
			);
			if($_FILES['avatar']['name'] != NULL){
				$config['upload_path']   = './uploads/album';
				$config['allowed_types'] = 'jpg|png|jpeg|gif';
				$config['max_size']	= '1500';
				$config['max_width']  = '1024';
				$config['max_height']  = '1024';
				$config['encrypt_name'] = TRUE;
				$this->load->library('upload',$config);
				if(!$this->upload->do_upload("avatar")){
					$data = array('error' => $this->upload->display_errors());
					$data['data'] = "";
					$data["template"] = "album/add";
					$data["title"] = "Add album";
					$data['destinations'] = $this->model_albums->listdestina();
					$this->load->view("layout",$data);
					return FALSE;
				}else{
					$data = $this->upload->data();
					$db['avatar'] = $data['file_name'];
					$this->createThumbnail($db['avatar'],"album",160,140);
				}
			}
			$file = $_FILES['img']['name'];
			$img = array();
			$now = "";
			if(count($file) > 1){
				for($i=0;$i<count($file);$i++){
					$name = $_FILES['img']['name'][$i];
					$type = $_FILES['img']['type'][$i];
					$size = $_FILES['img']['size'][$i];
					if($type == "image/jpeg" || $type == "image/png" || $type == "image/gif"){
							$now = date("dmYhis");
							if(!file_exists("uploads/album/".$now)){
								mkdir("uploads/album/".$now,0777);
							}
							$db['forder'] = $now;
							move_uploaded_file($_FILES['img']['tmp_name'][$i],"uploads/album/".$now."/".$_FILES['img']['name'][$i]);
							$img[] = $_FILES['img']['name'][$i];
					}else{
						die("Invalid file type : ".$type);
					}
					//echo $name." - ".$type." - ".$size."<br />";
				}
				$db['fullimage'] = serialize($img);
			}
			$this->model_albums->add($db);
			redirect(base_url().'admin/album/index');
		}else{
			$this->load->view("layout",$data);
		}
	}
	public function update(){
		$id = $this->uri->segment(4);
		$data['data'] = "";
		$data["template"]= "album/edit";
		$data["title"] = "Update album";
		$data['destinations'] = $this->model_albums->listdestina();
		$data['getdata'] = $this->model_albums->getdata($id);
		$data['destinaid'] = $data['getdata']['destina_id'];
		$this->session->set_userdata("forder",$data['getdata']['forder']);
		if($this->input->post("ok")){
			$frienly = str_replace(' ', '-', strtolower($this->string->replace($this->input->post('title'))));
			$db = array(
				"title" => $this->input->post("title"),
				"rewrite" => $frienly,
				"keyword" => $this->input->post("keyword"),
				"description" => $this->input->post("description"),
				"createdate" => date("d/m/Y H:i:s"),
				"destina_id" => $this->input->post("destina_id")
			);
			if($_FILES['avatar']['name'] != NULL){
				$config['upload_path']   = './uploads/album';
				$config['allowed_types'] = 'jpg|png|jpeg|gif';
				$config['max_size']	= '1500';
				$config['max_width']  = '1024';
				$config['max_height']  = '1024';
				$config['encrypt_name'] = TRUE;
				$this->load->library('upload',$config);
				if(!$this->upload->do_upload("avatar")){
					$data = array('error' => $this->upload->display_errors());
					$data['data'] = "";
					$data["template"]= "album/edit";
					$data["title"] = "Update album";
					$data['destinations'] = $this->model_albums->listdestina();
					$data['getdata'] = $this->model_albums->getdata($id);
					$data['destinaid'] = $data['getdata']['destina_id'];
					$this->load->view("layout",$data);
					return FALSE;
				}else{
					$data = $this->upload->data();
					$db['avatar'] = $data['file_name'];
					$this->createThumbnail($db['avatar'],"album",160,140);
				}
			}
			$file = $_FILES['img']['name'];
			$img = array();
			$now = "";
			if(count($file) > 1){
				for($i=0;$i<count($file);$i++){
					$name = $_FILES['img']['name'][$i];
					$type = $_FILES['img']['type'][$i];
					$size = $_FILES['img']['size'][$i];
					if($type == "image/jpeg" || $type == "image/png" || $type == "image/gif"){
							$now = date("dmYhis");
							if(!file_exists("uploads/album/".$now)){
								mkdir("uploads/album/".$now,0777);
							}
							$db['forder'] = $now;
							move_uploaded_file($_FILES['img']['tmp_name'][$i],"uploads/album/".$now."/".$_FILES['img']['name'][$i]);
							$img[] = $_FILES['img']['name'][$i];
					}else{
						die("Invalid file type : ".$type);
					}
					//echo $name." - ".$type." - ".$size."<br />";
				}
				$db['fullimage'] = serialize($img);
				$this->rmforder($this->session->userdata("forder"),"uploads/album");
			}
			$this->model_albums->update($db,$id);
			redirect(base_url().'admin/album/index');
			
		}else{
			$this->load->view("layout",$data);
		}
	}
	public function del($id){
		$data = $this->model_albums->getdata($id);
		if($data == NULL){ die("This album is not avaible");}
		$this->rmforder($data['forder'],"uploads/album");
		$this->model_albums->del($id);
		redirect(base_url().'admin/album/index');
	}
	public function rmforder($forder,$parth){
		$dirPath = $parth."/".$forder;
		if(file_exists($dirPath)){
			if(! is_dir($dirPath)) {
				throw new InvalidArgumentException("$dirPath must be a directory");
			}
			if(substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
				$dirPath .= '/';
			}
			$files = glob($dirPath . '*', GLOB_MARK);
			foreach ($files as $file) {
				if (is_dir($file)) {
					@rmdir($file);
				} else {
					@unlink($file);
				}
			}
			@rmdir($dirPath);
		}
	}
	public function createThumbnail($fileName,$path,$width,$height,$islocksize=true){
			$this->load->library('image_lib');
			$config['image_library'] = 'gd2';
			$config['source_image'] = 'uploads/'.$path.'/'.$fileName;
			$config['new_image']    = 'uploads/'.$path.'/thumb/'.$fileName;
			$config['create_thumb'] = TRUE;
			$config['maintain_ratio'] = $islocksize;
			$config['thumb_marker'] = FALSE;
			$config['width'] = $width;
			$config['height'] = $height;
			$this->image_lib->initialize($config); 
			$this->image_lib->resize();
			$this->image_lib->clear();
	}
}